package com.erpanderp.wam.usm.view.leave;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import com.erpanderp.wam.cm.model.entity.EmpPersonalResume;
import com.erpanderp.wam.usm.model.entity.leave.EmployeeLeave;
import com.erpanderp.wam.usm.model.entity.leave.LeaveBalance;
import com.erpanderp.wam.usm.model.entity.leave.LeaveType;
import com.erpanderp.wam.usm.model.entity.timesheet.TimesheetDetail;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.EmployeeLeaveDAO;
import com.erpanderp.wam.usm.model.service.leave.LeaveBalanceDAO;
import com.erpanderp.wam.usm.model.service.timesheet.TimesheetDetailDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ManagedBean
@ViewScoped
public class ApproveCancelledLeaveBean implements Serializable {
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);
	HttpServletRequest request = (HttpServletRequest) FacesContext
			.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	private String leaveCODE;
	private EmployeeLeaveDAO employeeLeaveDAO;
	private EmployeeLeave employeeLeave = new EmployeeLeave();
	private boolean leaveCancelRequestApprovedAlready;
	private static final long serialVersionUID = 1L;
	private LeaveType leaveType = new LeaveType();
	private boolean FORM_VALID;
	private WAMUser wamUser = new WAMUser();
	private EmailUtil emailUtil;
	private String leaveApprovedAlready;
	private boolean leaveApprovedFlag = true;
	private LeaveBalance leaveBalance = new LeaveBalance();
	private Float addingLeaves;
	private Float toBeAddedLeaves;
	private LeaveBalanceDAO leaveBalanceDAO = new LeaveBalanceDAO();
	private HtmlOutputText leaveApprovedAlreadyHtmlOutputText = new HtmlOutputText();
	private SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
	private String leaveFromToBeDisplayed;
	private String leaveToToBeDisplayed;
	private EmployeeAndReporting employeeAndReporting = new EmployeeAndReporting();
	private EmployeeAndReportingDAO employeeAndReportingDAO = new EmployeeAndReportingDAO();

	public ApproveCancelledLeaveBean() {
		wamUser = (WAMUser) session
				.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);

		System.out.println("IN APPROVE CANCELLED LEAVE BEAN CONSTRUCTOR");
		System.out.println("IN APPROVE LEAVE ACTION");
		leaveCODE = request.getParameter("leaveCODE");
		employeeLeaveDAO = new EmployeeLeaveDAO();
		employeeLeave = employeeLeaveDAO.getEmployeeLeaveByLeaveCODE(leaveCODE);
		  employeeAndReporting =
				  employeeAndReportingDAO.getEmployeeReportingDetail(employeeLeave.getEmployee().getEmployeeId());
				
		System.out.println("EMPLOYEE LEAVE TYPE IN CONSTRUCTOR------------> ="+employeeLeave.getLeaveType().getLeaveType());
		leaveFromToBeDisplayed = formatter
				.format(employeeLeave.getPeriodFrom());
		leaveToToBeDisplayed = formatter.format(employeeLeave.getPeriodTo());
		if (employeeLeave.getApprovalStatus().equals(CommonLookup.LEAVE_EMP_CANCELLED_STATUS)
				|| employeeLeave.getApprovalStatus().equals(CommonLookup.LEAVE_PM_CANCELLED_STATUS)) {
			System.out.println("LEAVE CANCEL REQUEST APPROVED/REJECTED BEFORE");

			leaveCancelRequestApprovedAlready = false;
		} else {
			leaveCancelRequestApprovedAlready = true;

		}

	}

	public void leveCancelRequestApprovedORRejectAction(ActionEvent actionEvent) throws IOException {
		UIComponent uiData = actionEvent.getComponent();
		String messageString = null;

		String leaveFROM = formatter.format(employeeLeave.getPeriodFrom());
		String leaveTO = formatter.format(employeeLeave.getPeriodTo());
		System.out.println("ACTION COMMAND  IS :"
				+ actionEvent.getComponent().getId());

		validate();
		if (FORM_VALID) {

			if (actionEvent.getComponent().getId().equals("Accept")) {
			    employeeLeave.setApprovalStatus(CommonLookup.LEAVE_PM_CANCELLED_STATUS);
				// employeeLeave.setCancellationStatus(CommonLookup.LEAVE_CANCELLATION_APPROVED_STATUS);

				addingLeaves = Float.valueOf(employeeLeave.getNoOfDays());
				leaveBalance = leaveBalanceDAO.getActualLeaveBalanceByLeaveTypeIdAndEmployeeId(
								employeeLeave.getLeaveType().getLeaveTypeid(),employeeLeave.getEmployee().getEmployeeId());
				if (employeeLeave.getLeaveType().getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)) {
					toBeAddedLeaves = leaveBalance.getBalance()-addingLeaves;
				} else if (employeeLeave != null && employeeLeave.getLeaveType().getLeaveType()
								.equals(CommonLookup.LOSS_OF_PAY_TYPE)) {
					addingLeaves = Float.valueOf(employeeLeave.getNoOfDays());
					toBeAddedLeaves = leaveBalance.getBalance()-addingLeaves;

				}else if(employeeLeave != null && employeeLeave.getLeaveType().getLeaveType().equals(CommonLookup.COMP_OF_TYPE)){
		            System.out.println("COMP OFF LEAVE TYPE IN IF"+employeeLeave.getLeaveType().getLeaveType()); 
					addingLeaves = Float.valueOf(employeeLeave.getNoOfDays());
					toBeAddedLeaves = leaveBalance.getBalance()-addingLeaves;

				}else{
					System.out.println("COMP OFF LEAVE TYPE IN ELSE "+employeeLeave.getLeaveType().getLeaveType());
					addingLeaves = Float.valueOf(employeeLeave.getNoOfDays());
					toBeAddedLeaves = leaveBalance.getBalance()+addingLeaves;
				}
				leaveBalance.setBalance(toBeAddedLeaves);
				leaveBalance.getLeaveType().setLeaveTypeid(
						employeeLeave.getLeaveType().getLeaveTypeid());
				leaveBalanceDAO.updateLeaveBalance(leaveBalance);

			} else {
				employeeLeave.setApprovalStatus(CommonLookup.LEAVE_REJECT_STATUS);
			}
			
			if(actionEvent.getComponent().getId().equals("Accept")){
				   employeeLeaveDAO.leaveApprovedByApprovalComments(employeeLeave);
				   updateTimesheetDetailStatusIfExist();
				}else{
					employeeLeaveDAO.leaveApprovedByApprovalComments(employeeLeave);
				}
			
			

			Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			emailUtil = new EmailUtil();
			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
				System.out.println("PRODUCTION");
				String[] to = { employeeLeave.getEmployee().getEmail() };
				emailUtil.setRecieverAddresses(to);				
			} else {
				System.out.println("DEVELOPMENT");
				String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
				emailUtil.setRecieverAddresses(to);				
			}

			String subject = null;
			if (actionEvent.getComponent().getId().equals("Accept")) {
				subject = employeeLeave.getEmployee().getFirstName() + " ("
						+ leaveCODE + ") "
						+ " Leave Cancellation Request is Approved";
				messageString = "Dear "
						+ employeeLeave.getEmployee().getFirstName() + " "
						+ employeeLeave.getEmployee().getLastName()
						+ ",<br /><br />" +

						"<table border='0'>"
						+ "<tr> <td>Leave Description </td><td> : </td><td>"
						+ employeeLeave.getReasonForCancel() + " </td></tr>"
						+ "<tr> <td>Leave Type</td><td> : </td> <td>"
						+ employeeLeave.getLeaveType().getLeaveType()
						+ "</td></tr>" +

						"</table><br/><br/>" +

						"your leave cancellation request is  from "
						+ leaveFROM + " TO " + leaveTO
						+ " with approver comments : "
						+ employeeLeave.getCancellationComments()
						+ "<br /><br />" +

						"Thanks & Regards, <br />"
						+ CommonLookup.WAM_DEVTEAM_SIGNATURE;
			} else {
				System.out.println("COMPONENT ID IS :"
						+ actionEvent.getComponent().getId());
				subject = employeeLeave.getEmployee().getFirstName() + " ("
						+ leaveCODE + ") "
						+ " Leave Cancellation Request is Rejected";
				messageString = "Dear "
						+ employeeLeave.getEmployee().getFirstName() + " "
						+ employeeLeave.getEmployee().getLastName()
						+ ",<br /><br />" +

						"<table border='0'>"
						+ "<tr> <td>Leave Description </td><td> : </td><td>"
						+ employeeLeave.getReasonForCancel() + " </td></tr>"
						+ "<tr> <td>Leave Type</td><td> : </td> <td>"
						+ employeeLeave.getLeaveType().getLeaveType()
						+ "</td></tr>" +

						"</table><br/><br/>" +

						"your leave cancellation request is rejected from "
						+ leaveFROM + " TO " + leaveTO
						+ " with approver comments : "
						+ employeeLeave.getCancellationComments()
						+ "<br /><br />" +

						"Thanks & Regards, <br />"
						+ CommonLookup.WAM_DEVTEAM_SIGNATURE;
			}
			// emailUtil.setRecieverAddresses();
			emailUtil.setMessage(messageString);
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
			emailUtil.setSubject(subject);

			if (actionEvent.getComponent().getId().equals("Accept")) {

				FacesContext
						.getCurrentInstance()
						.addMessage(
								null,
								new FacesMessage(
										FacesMessage.SEVERITY_INFO,
										" Leave cancellation request has been  approved successfully.",
										""));
			} else {
				FacesContext
						.getCurrentInstance()
						.addMessage(
								null,
								new FacesMessage(
										FacesMessage.SEVERITY_INFO,
										" Leave cancellation request has been rejected.",
										""));
			}

			SwingWorker worker = new SwingWorker<String, Object>() {

				@Override
				protected String doInBackground() throws Exception {
					// TODO Auto-generated method stub

					emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
					// TODO Auto-generated method stub
					System.out.println("MAIL SENT");
					// super.done();
				}
			};
			worker.execute();

			employeeLeave = new EmployeeLeave();
			
		} else {
			
		}
		

	}
	
	private boolean updateTimesheetDetailStatusIfExist(){
		boolean UPDATED = false;
		System.out.println("trying to update timesheet...");
		try{
			TimesheetDetailDAO timesheetDetailDAO = new TimesheetDetailDAO();
			List<TimesheetDetail> timesheetDetails = (List<TimesheetDetail>) timesheetDetailDAO.getTimesheetDetails(employeeLeave.getPeriodFrom(), employeeLeave.getPeriodTo(), employeeLeave.getEmployee().getEmployeeId());
			System.out.println(timesheetDetails != null ? timesheetDetails.size() : "ZEROOOOOOOOOOOO");
			Date now = new Date();
			for(TimesheetDetail timesheetDetail : timesheetDetails){
				timesheetDetail.setDateModified(now);
				timesheetDetail.setModifiedBy(wamUser.getEmployee().getFirstName());
				timesheetDetail.setTimesheetDetailStatus("P");
				
				timesheetDetailDAO.updateTimesheetDetail(timesheetDetail);
				
			}
			return UPDATED;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}				
	}
	
	

	public boolean validate() {
		System.out.println("IN VALIDATE METHOD");
		FORM_VALID = true;
		if (ValidationUtil.isEmpty(employeeLeave.getCancellationComments(),
				"Cancellation Comments", null,
				FacesContext.getCurrentInstance()) != null) {
			System.out.println("LEAVE APPROVAL STATUS IS EMPTY");

			FORM_VALID = false;

		}

		return FORM_VALID;
	}

	public String getLeaveCODE() {
		return leaveCODE;
	}

	public void setLeaveCODE(String leaveCODE) {
		this.leaveCODE = leaveCODE;
	}

	public EmployeeLeaveDAO getEmployeeLeaveDAO() {
		return employeeLeaveDAO;
	}

	public void setEmployeeLeaveDAO(EmployeeLeaveDAO employeeLeaveDAO) {
		this.employeeLeaveDAO = employeeLeaveDAO;
	}

	public EmployeeLeave getEmployeeLeave() {
		return employeeLeave;
	}

	public void setEmployeeLeave(EmployeeLeave employeeLeave) {
		this.employeeLeave = employeeLeave;
	}

	public boolean isLeaveCancelRequestApprovedAlready() {
		return leaveCancelRequestApprovedAlready;
	}

	public void setLeaveCancelRequestApprovedAlready(
			boolean leaveCancelRequestApprovedAlready) {
		this.leaveCancelRequestApprovedAlready = leaveCancelRequestApprovedAlready;
	}

	public boolean isFORM_VALID() {
		return FORM_VALID;
	}

	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public EmailUtil getEmailUtil() {
		return emailUtil;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public String getLeaveApprovedAlready() {
		return leaveApprovedAlready;
	}

	public void setLeaveApprovedAlready(String leaveApprovedAlready) {
		this.leaveApprovedAlready = leaveApprovedAlready;
	}

	public boolean isLeaveApprovedFlag() {
		return leaveApprovedFlag;
	}

	public void setLeaveApprovedFlag(boolean leaveApprovedFlag) {
		this.leaveApprovedFlag = leaveApprovedFlag;
	}

	public LeaveBalance getLeaveBalance() {
		return leaveBalance;
	}

	public void setLeaveBalance(LeaveBalance leaveBalance) {
		this.leaveBalance = leaveBalance;
	}

	public LeaveBalanceDAO getLeaveBalanceDAO() {
		return leaveBalanceDAO;
	}

	public void setLeaveBalanceDAO(LeaveBalanceDAO leaveBalanceDAO) {
		this.leaveBalanceDAO = leaveBalanceDAO;
	}

	public HtmlOutputText getLeaveApprovedAlreadyHtmlOutputText() {
		return leaveApprovedAlreadyHtmlOutputText;
	}

	public void setLeaveApprovedAlreadyHtmlOutputText(
			HtmlOutputText leaveApprovedAlreadyHtmlOutputText) {
		this.leaveApprovedAlreadyHtmlOutputText = leaveApprovedAlreadyHtmlOutputText;
	}

	public SimpleDateFormat getFormatter() {
		return formatter;
	}

	public void setFormatter(SimpleDateFormat formatter) {
		this.formatter = formatter;
	}

	public LeaveType getLeaveType() {
		return leaveType;
	}

	public void setLeaveType(LeaveType leaveType) {
		this.leaveType = leaveType;
	}

	public Float getAddingLeaves() {
		return addingLeaves;
	}

	public void setAddingLeaves(Float addingLeaves) {
		this.addingLeaves = addingLeaves;
	}

	public Float getToBeAddedLeaves() {
		return toBeAddedLeaves;
	}

	public void setToBeAddedLeaves(Float toBeAddedLeaves) {
		this.toBeAddedLeaves = toBeAddedLeaves;
	}

	public String getLeaveFromToBeDisplayed() {
		return leaveFromToBeDisplayed;
	}

	public void setLeaveFromToBeDisplayed(String leaveFromToBeDisplayed) {
		this.leaveFromToBeDisplayed = leaveFromToBeDisplayed;
	}

	public String getLeaveToToBeDisplayed() {
		return leaveToToBeDisplayed;
	}

	public void setLeaveToToBeDisplayed(String leaveToToBeDisplayed) {
		this.leaveToToBeDisplayed = leaveToToBeDisplayed;
	}

	public EmployeeAndReporting getEmployeeAndReporting() {
		return employeeAndReporting;
	}

	public void setEmployeeAndReporting(EmployeeAndReporting employeeAndReporting) {
		this.employeeAndReporting = employeeAndReporting;
	}

}
